package com.sevenGroup.pawnshop.config;

import com.sevenGroup.pawnshop.dao.UsersDao;
import com.sevenGroup.pawnshop.handle.failHandler;
import com.sevenGroup.pawnshop.handle.successHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder addPasswordEncord() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/login", "/login.do", "/users/nologin", "/logout",
                        "/swagger-ui.html","/v2/api-docs","/webjars/**", "/swagger-resources/**","/stores/GetURL").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/users/nologin")
                .loginProcessingUrl("/login")
                .successHandler(new successHandler())
                .failureHandler(new failHandler())
                .and()
                .cors().configurationSource(setCorsConfig())
        ;
    }

    public UrlBasedCorsConfigurationSource setCorsConfig() {
        CorsConfiguration ccf = new CorsConfiguration();
        ccf.addAllowedHeader("*");
        ccf.addAllowedMethod("*");
        ccf.setAllowCredentials(true);
        ccf.addAllowedOriginPattern("*");
        UrlBasedCorsConfigurationSource uccf = new UrlBasedCorsConfigurationSource();
        uccf.registerCorsConfiguration("/**",ccf);
        return uccf;
    }
}